package com.tsingtao.springboot2.service.impl;

import com.tsingtao.springboot2.dto.Document;
import com.tsingtao.springboot2.model.DocumentMapper;
import com.tsingtao.springboot2.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.annotation.rely.FieldType;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.index.LambdaEsIndexWrapper;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DocumentServiceImpl implements DocumentService {

    @Autowired
    private DocumentMapper documentMapper;

    @Override
    public Boolean createIndex(Document document) {
        Boolean isExists = documentMapper.existsIndex("document");
        if(!isExists) {
            Boolean index = documentMapper.createIndex();
            log.info("索引创建是否成功：{}", index);
            return index;
        } else {
            return true;
        }
    }

    @Override
    public Boolean testCreateIndexByWrapper() {
        LambdaEsIndexWrapper<Document> wrapper = new LambdaEsIndexWrapper<>();
        // 此处简单起见 索引名称须保持和实体类名称一致,字母小写 后面章节会教大家更如何灵活配置和使用索引
        wrapper.indexName(Document.class.getSimpleName().toLowerCase());
        // 此处将文章标题映射为keyword类型(不支持分词),文档内容映射为text类型(支持分词查询)
        wrapper.mapping(Document::getTitle, FieldType.KEYWORD)
                .mapping(Document::getContent, FieldType.TEXT);
        // 创建索引
        boolean isOk = documentMapper.createIndex(wrapper);
        log.info("索引创建是否成功：{}", isOk);
        return isOk;
    }

    @Override
    public Document testInsert(Document document) {
        Integer insert = documentMapper.insert(document);
        log.info("文档插入是否成功：{}", insert);
        return document;
    }

    @Override
    public List<Document> selectList(LambdaEsQueryWrapper<Document> wrapper) {
        wrapper.eq(Document::getTitle, "t1");
        return documentMapper.selectList(wrapper);
    }

    @Override
    public Boolean testUpdateIndex() {
        // 测试更新索引
        LambdaEsIndexWrapper<Document> wrapper = new LambdaEsIndexWrapper<>();
        // 指定要更新哪个索引
        String indexName = Document.class.getSimpleName().toLowerCase();
        wrapper.indexName(indexName);
        wrapper.mapping(Document::getGmtCreate, FieldType.DATE);
        boolean isOk = documentMapper.updateIndex(wrapper);
        return isOk;
    }

    @Override
    public EsPageInfo<Document> testEsPage(EsPageInfo<Document> pageInfo, Document document) {
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        return documentMapper.pageQuery(wrapper, pageInfo.getPageNum(), pageInfo.getPageSize());
    }
}
